//

import Koa from 'koa'
import { Success, HttpException } from '@/core/HttpException'
import { errorLog, infoLog } from '@/server/logs'
export async function catchError(ctx: Koa.Context, next: Function) {
  try {
    await next()
  } catch (error: any) {
    // 当前错误是否是否是我们自定义的http错误
    const isHttpException = error instanceof HttpException
    // 如果不是 则抛出异常
    if (!isHttpException) {
      errorLog(ctx, error)
      const { method, path } = ctx
      ctx.body = {
        msg: '未知错误',
        errorCode: 9999,
        requestUrl: `${method} ${path}`,
      }
      ctx.status = 500
    } else {
      // 如果是已知错误
      if (error.responseType) {
        ctx.response.type = error.responseType
      }
      if (error.isBuffer) {
        ctx.body = error.data
      } else {
        ctx.body = {
          // msg: error.message,
          // errorCode: error.errorCode,
          // data: error.data,
          // code:error.code
          ...error,
        }
      }
      ctx.status = error.code
      if (error instanceof Success || error instanceof Buffer) {
        infoLog(ctx)
      } else {
        errorLog(ctx, error)
      }
    }
  }
}
